import React, { useState, useEffect,useRef } from "react";
import LlxTable from 'components/LlxTable'
import LlxForm from 'components/LlxForm/index'
import { Form ,Button,notification,Select,Divider,DatePicker,Modal,message} from 'antd';
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries,checkPublishData} from 'redux/action'

import PushTheme from 'components/LlxPushData/theme'
import {queryRankById,updateUserLessonBatch,delUserLesson,userThemePush} from 'api/index'
import classNames from "classnames";


import commonConfig from "static/js/commonConfig";
const { RangePicker } = DatePicker;

// 新增编辑新名称
const AddNewName = (props) =>{
  const {isModalVisible, setIsModalVisible,userName,form} = props

  const loading = useRef(false)
  console.log(form.getFieldValue());

  // 新增表单
const newWordItem = [
  {label: '新课程名称',type:'input', name: 'lessonAppName' , span: 20,rules:[
    {
      required: true,
      message: '请输入新课程名称'
    },
  ]}
]

  const handleOk = () => {
    if(loading.current) return
    
    loading.current=true
    form.validateFields().then(async()=>{

      if(form.getFieldValue().id){
        await updateUserLessonBatch([form.getFieldValue()])
        notification.success({
          message: '编辑成功',
          description: '操作人：' + userName,
          duration:1.5
        });
      } else {
        await userThemePush(form.getFieldValue())
        notification.success({
          message: '新增成功',
          description: '操作人：' + userName,
          duration:1.5
        });
      }

      form.resetFields()
      setIsModalVisible(false);

      props.getNewList()
    }).catch(err=>{
      notification.warning({
        message: '检查必填项',
        duration:1.5
      });
    }).finally(()=>{
      loading.current=false
    })
  };

  const handleCancel = () => {
    form.resetFields()
    setIsModalVisible(false);
  };

  return   <Modal width={700} title="新课程名称" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <LlxForm form={form} labelCol={8} formItem={newWordItem} />
   </Modal>
} 

const formItems = (dictionaries,getUpdateTime) => {
  return [
      {label: '名称',type:'input', name: 'lessonName', span: 4 },
      {label: '题数', name: 'subjectCount', span: 5,render: () => {
        return <Select
        allowClear
        optionFilterProp="dictValue"
        showSearch
        fieldNames={{value:'id',label:'dictValue'}}
        placeholder={'请选择题数'}
      options={dictionaries.CountNumber}
   >
   </Select> }},
      {label: '课程ID',type:'input', name: 'lessonCode', span: 5 },
      {label: '词汇',type:'input', name: 'words', span: 5 },
      {label: '目标描述',type:'input', name: 'remark', span: 5 },
      {label: '句型',type:'input', name: 'sentencePattern', span: 4 },
      {label: '拼读单词',type:'input', name: 'lessonReading', span: 5 },
      {label: '字母',type:'input', name: 'letter', span: 5 },
      {label: '创建人', name: 'createBy',  span: 5 ,render: () => {
         return <Select
         allowClear
         optionFilterProp="userName"
         showSearch
         fieldNames={{value:'userName',label:'userName'}}
         placeholder={'请选择创建人'}
      options={dictionaries.UserSpecies}
    >
    </Select>
      }},
        {label: '更新人', name: 'updateBy',  span: 5,render: () => {
        return <Select
        allowClear
        optionFilterProp="userName"
        showSearch
        fieldNames={{value:'userName',label:'userName'}}
      placeholder={'请选择更新人'}
      options={dictionaries.UserSpecies}
    >
    </Select>
      }},
       {label: '更新时间', name: 'updateTime', span: 5 ,render: () => {
      return  <RangePicker showTime onChange={getUpdateTime} style={{width:'100%'}}/>
      }}
  ]
}

function UserThemeLibrary(props) {
const {dictionaries} = props

// 数据
const [loading,setLoading] = useState(false) //加载
const [expand,setExpand] = useState(false) //表单伸缩
const [total,setTotal] = useState(0) //总数量
const [isModalVisible, setIsModalVisible] = useState(false)
const [isModalVisibleName, setIsModalVisibleName] = useState(false)
const [form] = Form.useForm();//搜索列表
const [formName] = Form.useForm();

//选择数据
const [selectedRowKeys,setselectedRowKeys] = useState([])
const rowSelection  = useRef({
  selectedRowKeys: selectedRowKeys,
  onChange: value => {
  setselectedRowKeys(value)
  rowSelection.current.selectedRowKeys = value
  }
})

// 7.获取时间
const getUpdateTime = (value,dataString) => {
  const data = form.getFieldValue()
  data.startTime=dataString[0]
  data.endTime=dataString[1]
  form.setFieldsValue(data)
}


// 表单数据
const formItem =formItems(dictionaries,getUpdateTime)
//分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:20
})
//初始表格数据
const [dataSource,setDataSource] = useState([])
//表头配置信息
const columns = [
      {title: '序号',fixed:'left',  dataIndex: 'sort', key: 'sort', align: 'center',width:50},
      {title: '名称',fixed:'left', dataIndex: 'lessonName',width:150, key: 'lessonName', align: 'center',render: (text, record) => {
        return <div className="operate_link_group text-nowrap text-link" onClick={()=>goThemeInfo(record.flowId)}>
          {text}
       </div>
     }},
      {title: '新课程名称', dataIndex: 'lessonAppName',width:150, key: 'lessonAppName', align: 'center'},
      {title: '课程ID', dataIndex: 'lessonCode',width:150, key: 'lessonCode', align: 'center'},
      {title: '字母', dataIndex: 'letter',width:100, key: 'letter', align: 'center'},
      {title: '词汇', dataIndex: 'words',width:150, key: 'words', align: 'center'},
      {title: '题数', dataIndex: 'count',width:50, key: 'count', align: 'center'},
      {title: '拼读单词', dataIndex: 'lessonReading',width:150, key: 'lessonReading', align: 'center'},
      {title: '句型', dataIndex: 'sentencePattern',width:150, key: 'sentencePattern', align: 'center'},
      {title: '目标描述', dataIndex: 'remark',width:150, key: 'remark', align: 'center'},
      {title: '创建人',width:120, dataIndex: 'createBy', key: 'createBy', align: 'center',render: (text, record) => {
        return <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
          {text}
       </div>
      }},
      {title: '更新人',width:120, dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
        return  <div className={classNames(props.userInfo.user.userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
        {text}
     </div>
      }},
      {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:150},
      {title: '操作',fixed:'right', dataIndex: 'active', key: 'active', align: 'center',width:150,render:(text,row)=>{
        return <div>
          <span className="text-link" onClick={()=>editTheme(row)}>编辑</span>&nbsp;&nbsp;&nbsp;
          <span className="text-link" onClick={()=>goTop(row)}>上移</span>&nbsp;&nbsp;&nbsp;
          <span className="text-link" onClick={()=>goBottom(row)}>下移</span>
        </div>
      }}
]
     
     
// 初始化
//1缓存页面数据 缓存表单数据
useEffect(()=>{
  form.setFieldsValue(props.tabList.filter(i=>i.url==='plan/userCounrseSubjectList')[0]?.data?.form)
  setPagination(props.tabList.filter(i=>i.url==='plan/userCounrseSubjectList')[0]?.data?.pagination||{
    current:1,
    pageSize:20
  })
  },[]) // eslint-disable-line react-hooks/exhaustive-deps


// 切换发布草稿素材
useEffect(()=>{
  // 获取数据
  getNewList()

  
},[props.examineStatus]) // eslint-disable-line react-hooks/exhaustive-deps

// 方法
// 1.获取数据
const getNewList=(value)=>{
  setIsModalVisible(false)
  // 清空选中状态
   setselectedRowKeys(()=>[])
   rowSelection.current.selectedRowKeys=[]

   setLoading(true)

  // 缓存数据
   const data = {
     pagination: value&&value.pageSize?value:pagination,
     form:form.getFieldValue()
  }
    props.setPageDataFn('plan/userCounrseSubjectList?' + window.location.href.slice(window.location.href.indexOf('id=')),data) 

    const initialData = async () => {
      const params = form.getFieldValue()
      params.currPage=value&&value.pageSize?value.current:pagination.current
      params.pageSize=value&&value.pageSize?value.pageSize:pagination.pageSize
    

      if (params.subjectCount === 0 || params.subjectCount) {
        params.countBg = params.subjectCount
        params.countEd = params.subjectCount !== 50 ? params.subjectCount + 5 : 1000
      }

      params.rankId = commonConfig.getUrlParams(props).id


        const res = await queryRankById(params)
        const data = res.result.records || []

        setDataSource(data)
  
        setTotal(res.result.total)
      }
    

    setLoading(false)
    
    initialData()
 }
 // 2.重置表单
 const resetForm=()=>{
   form.resetFields()
   setPagination({
    current:1,
    pageSize:20
  })
   getNewList()
 }
//  4.主题课详情
const goThemeInfo = (id) => {
  props.checkPublishDataBtn()
props.history.push('/view/plan/themeSubjectInfo?id=' + id)
props.addRouter({
  menuName:'主题课详情',url:'plan/themeSubjectInfo?id=' + id 
})
}
//  5.新增用户主题
const addNewUserTheme = () => {
  setIsModalVisible(true)
}
// 6.编辑
const editTheme = (value) => {
  formName.setFieldsValue({
    id:value.id,
    dataId:'',
    lessonAppName:value.lessonAppName
  })
  setIsModalVisibleName(true)
}
// 7.删除
const delUserTheme = async () => {
  const res = await delUserLesson(selectedRowKeys.map(i => {
    return {
      id: i,
      status: 0
    }
  }))
    notification.success({
      message: res.message,
      duration:3
    });

    getNewList()
}
// 8.上移
const goTop = async(data) => {
  if (dataSource.findIndex(i => i.id === data.id) === 0) {
    message.error('第一个不可移动')
    return
  }
  await updateUserLessonBatch([{ id: data.id, sort: data.sort - 1 }, { id: dataSource[dataSource.findIndex(i => i.id === data.id) - 1].id, sort: data.sort }])
  getNewList()
}
// 9.下移
const goBottom = async(data) => {
  if (dataSource.findIndex(i => i.id === data.id) === dataSource.length - 1) {
    message.error('最后一个不可移动，请调整条数')
    return
  }
  await updateUserLessonBatch([{ id: data.id, sort: data.sort + 1 }, { id: dataSource[dataSource.findIndex(i => i.id === data.id) + 1].id, sort: data.sort }])
  getNewList()
}
// 10新增
const returnThemeId = (value) => {
  formName.setFieldsValue({
    id:'',
    dataId: [value],
    lessonAppName: '',
    levelAppId: commonConfig.getUrlParams(props).levelAppId,
    rankId: commonConfig.getUrlParams(props).id
  })
  setIsModalVisibleName(true)
}

return <div className="app-content animate__animated animate__fadeIn">
    {/* 表单 */}
    <LlxForm form={form} formItem={expand?formItem:formItem.filter((i,j)=>j<5)}/>
    {/* 操作按钮 */}
    <div className="operate-btn">
        <div>
        <Button  onClick={addNewUserTheme} type='primary' className='animate__animated animate__fadeInLeft'>新增</Button>
        <Button disabled={!selectedRowKeys.length}  onClick={delUserTheme} type='primary' danger className='animate__animated animate__fadeInLeft'>删除</Button>
       </div>

   

       <div>
         <Button  onClick={getNewList} type='primary' className='animate__animated animate__fadeInRight'>查询</Button>
          <Button  type='primary' onClick={resetForm} className='animate__animated animate__fadeInRight'>重置</Button>
          <Button  type='link' onClick={()=>setExpand(i=>!i)} className='animate__animated animate__fadeInRight'>{expand?'收起':'展开'}</Button>
       </div>

    </div>
     
    <Divider style={{color:'red'}}>用户级别{commonConfig.getUrlParams(props).levelAppName}</Divider>
    {/* 表格 */}
    <LlxTable
     loading={loading} 
     pagination={pagination}
     setPagination={setPagination}
     selectedRowShow={true}
     rowSelection={rowSelection.current}
     height={!expand?310:420}
     total={total}
     getNewList={getNewList}
     columns={columns}
     dataSource={dataSource}/>

     {/* 弹框 */}

     
     <PushTheme returnThemeId={returnThemeId} title={'新增用户主题课'} setIsModalVisible={setIsModalVisible} multipleType={false} userName={props.userInfo.user.userName}  dictionaries={dictionaries}  isModalVisible={isModalVisible}></PushTheme>
     <AddNewName getNewList={getNewList} form={formName} dictionaries={dictionaries} userName={props.userInfo.user.userName}  isModalVisible={isModalVisibleName} setIsModalVisible={setIsModalVisibleName}></AddNewName>
  </div>
}

// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    checkPublishDataBtn: () => dispatch(checkPublishData()),
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(UserThemeLibrary)
